
<!DOCTYPE html>
<html lang="zh-Hans" class="loading">
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>TypeScript 的好处都有啥？和 JavaScript 的区别在哪？ - 默默默默燃</title>
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="google" content="notranslate" />
    <meta name="keywords" content="TriDiamond Obsidian,"> 
    <meta name="description" content="一枚前端搬砖队队员的记录册,原文地址
在我看来 TypeScript 相对于 JavaScript ，除了静态类型外没带来任何东西。
既然如此
静态类型有什么好处静态类型的好处到处都有说，这里就不说得太详细了，随便列一点。

,"> 
    <meta name="author" content="张白告丶"> 
    <link rel="alternative" href="atom.xml" title="默默默默燃" type="application/atom+xml"> 
    <link rel="icon" href="/img/favicon.png"> 
    <link href="https://fonts.loli.net/css?family=Roboto+Mono|Rubik&display=swap" rel="stylesheet">
    
<link rel="stylesheet" href="//at.alicdn.com/t/font_1429596_nzgqgvnmkjb.css">

    
<link rel="stylesheet" href="//cdn.bootcss.com/animate.css/3.7.2/animate.min.css">

    
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/social-share.js/1.0.16/css/share.min.css">

    
<link rel="stylesheet" href="//cdn.bootcss.com/codemirror/5.48.4/codemirror.min.css">

    
<link rel="stylesheet" href="//cdn.bootcss.com/codemirror/5.48.4/theme/dracula.css">

    
<link rel="stylesheet" href="/css/obsidian.css">

    
<link rel="stylesheet" href="/css/ball-atom.min.css">

<meta name="generator" content="Hexo 4.2.0"></head>


<body class="loading">
    <div class="loader">
        <div class="la-ball-atom la-2x">
            <div></div>
            <div></div>
            <div></div>
            <div></div>
        </div>
    </div>
    <span id="config-title" style="display:none">默默默默燃</span>
    <div id="loader"></div>
    <div id="single">
    <div class="scrollbar gradient-bg-rev"></div>
<div id="top" style="display: block;">
    <div class="bar" style="width: 0;"></div>
    <div class="navigation animated fadeIn fast delay-1s">
        <img id="home-icon" class="icon-home" src="/img/favicon.png" alt="" data-url="https://zhanghao-web.github.io">
        <div id="play-icon" title="Play/Pause" class="iconfont icon-play"></div>
        <h3 class="subtitle">TypeScript 的好处都有啥？和 JavaScript 的区别在哪？</h3>
        <div class="social">
            <!--        <div class="like-icon">-->
            <!--            <a href="javascript:;" class="likeThis active"><span class="icon-like"></span><span class="count">76</span></a>-->
            <!--        </div>-->
            <div>
                <div class="share">
                    
                        <a href="javascript:;" class="iconfont icon-share1"></a>
                        <div class="share-component-cc" data-disabled="facebook,douban,linkedin,diandian,tencent,google"></div>
                    
                </div>
            </div>
        </div>
    </div>
</div>

    <div class="section">
        <div class=article-header-wrapper>
    <div class="article-header">
        <div class="article-cover animated fadeIn" style="
            animation-delay: 600ms;
            animation-duration: 1.2s;
            background-image: 
                radial-gradient(ellipse closest-side, rgba(0, 0, 0, 0.65), #100e17),
                url(/img/cover.jpg) ">
        </div>
        <div class="else">
            <p class="animated fadeInDown">
                
                <a href="/categories/Js"><b>「
                    </b>JS<b> 」</b></a>
                
                July 04, 2019
            </p>
            <h3 class="post-title animated fadeInDown"><a href="/2019/07/04/Ts/TypeScript-%E7%9A%84%E5%A5%BD%E5%A4%84%E9%83%BD%E6%9C%89%E5%95%A5%EF%BC%9F%E5%92%8C-JavaScript-%E7%9A%84%E5%8C%BA%E5%88%AB%E5%9C%A8%E5%93%AA%EF%BC%9F/" title="TypeScript 的好处都有啥？和 JavaScript 的区别在哪？" class="">TypeScript 的好处都有啥？和 JavaScript 的区别在哪？</a>
            </h3>
            
            <p class="post-count animated fadeInDown">
                
                <span>
                    <b class="iconfont icon-text2"></b> <i>Words count</i>
                    3.2k
                </span>
                
                
                <span>
                    <b class="iconfont icon-timer__s"></b> <i>Reading time</i>
                    3 mins.
                </span>
                
                
                
                <span id="busuanzi_container_page_pv">
                    <b class="iconfont icon-read"></b> <i>Read count</i>
                    <span id="busuanzi_value_page_pv">0</span>
                </span>
                
            </p>
            
            
            <ul class="animated fadeInDown post-tags-list" itemprop="keywords"><li class="animated fadeInDown post-tags-list-item"><a class="animated fadeInDown post-tags-list-link" href="/tags/Ts/" rel="tag">Ts</a></li></ul>
            
        </div>
    </div>
</div>

<div class="screen-gradient-after">
    <div class="screen-gradient-content">
        <div class="screen-gradient-content-inside">
            <div class="bold-underline-links screen-gradient-sponsor">
                <p>
                    <span class="animated fadeIn delay-1s"></span>
                </p>
            </div>
        </div>
    </div>
</div>

<div class="article">
    <div class='main'>
        <div class="content markdown animated fadeIn">
            <p><a href="https://zhuanlan.zhihu.com/p/38526585" target="_blank" rel="noopener">原文地址</a></p>
<p><strong>在我看来 TypeScript 相对于 JavaScript ，除了静态类型外没带来任何东西。</strong></p>
<p>既然如此</p>
<h2 id="静态类型有什么好处"><a href="#静态类型有什么好处" class="headerlink" title="静态类型有什么好处"></a>静态类型有什么好处</h2><p>静态类型的好处到处都有说，这里就不说得太详细了，随便列一点。</p>
<ul>
<li>杜绝手误导致的变量名错误</li>
<li>自动完成</li>
<li>重构支持</li>
<li>类型可以一定程度上充当文档</li>
</ul>
<p>静态类型解放脑容量，自动完成让我不需要记忆哪个变量里有哪些属性，也不需要记完整的变量名。</p>
<p>函数上的类型约束外加尽量主动写纯函数让我在写函数实现的时候不需要关注函数之外的任何东西，注意力聚焦在当前函数。</p>
<p>当然，也不只有好处。</p>
<h2 id="静态类型有什么不足"><a href="#静态类型有什么不足" class="headerlink" title="静态类型有什么不足"></a>静态类型有什么不足</h2><ul>
<li>类型标注麻烦。</li>
<li>现阶段大部分静态类型语言的类型系统还不够强。</li>
<li>eval 和 new Function() 这种骚操作类型系统管不到。</li>
<li>需要编译，类型检查会增加编译时长，语法和类型系统复杂的话时间特别特别长，比如 scala。</li>
</ul>
<p>标注麻烦的问题无法根绝，但是类型推导能解决大部分的类型标注问题。</p>
<p>类型系统不够强的问题会随着时间慢慢变好。</p>
<p>编译的问题在 ts 可能也并不算问题，ts 的类型检查并不影响 ts 编译成 js。</p>
<p>也就是说就算类型检查不通过 ts 也能跑起来。所以对 ts 来说类型检查可以从编译中提取出来，作为独立的编译和类型检查两部分。</p>
<p>先编译输出，再做类型检查，编译的部分相当于 babel 这种工具做的事。</p>
<p>类型检查也可以单独运行。</p>
<p>那么，</p>
<h2 id="TypeScript-的类型系统有哪些特点？"><a href="#TypeScript-的类型系统有哪些特点？" class="headerlink" title="TypeScript 的类型系统有哪些特点？"></a>TypeScript 的类型系统有哪些特点？</h2><ul>
<li><a href="https://link.zhihu.com/?target=https%3A//github.com/Microsoft/TypeScript/issues/14833">图灵完备</a>。（虽然不太清楚这意味着什么）</li>
<li>渐进的类型系统，所有类型标注都是可选的，既是天使又是恶魔的 <a href="https://link.zhihu.com/?target=https%3A//github.com/Microsoft/TypeScript/blob/master/doc/spec.md%233.1">any</a> 类型。（被 Haskell 大牛 <a href="https://www.zhihu.com/people/axurez" target="_blank" rel="noopener">Colliot</a> 称为 ts 类型系统的漏洞）</li>
<li>支持局部类型推导。</li>
<li>丰富的类型层面的计算，如 <a href="https://link.zhihu.com/?target=https%3A//www.typescriptlang.org/docs/handbook/advanced-types.html">index types, mapped types, conditional types</a> 等等。</li>
<li>支持<a href="">鸭子类型</a>。（或叫结构子类型？）</li>
<li>像 js 支持对象字面量一样支持方便的对象字面类型（object literal type），字符串和数字还有布尔值字面类型。</li>
<li>空安全。</li>
<li>基于控制流的类型分析</li>
</ul>
<p>还有许多我觉得比较平常的点就没有列出来，比如支持类型别名，泛型，协变逆变双变等等。</p>
<p>ts 是一门非常非常非常工程的语言，很强大，但是可能和优雅沾不上半点关系。</p>
<p>可选的类型标注搭配类型推导，让 ts 的类型系统更像是工具，而不是枷锁。好的产品是用完即走的。</p>
<p>有时候，稍微开个洞，能让事情变简单很多。比如 any。</p>
<p><code>鸭子类型</code>加上上面提到的特性可以让你依旧感觉和 js 一样，像大海里的鱼一样自由。</p>
<p><a href="https://link.zhihu.com/?target=https%3A//www.infoq.com/presentations/Null-References-The-Billion-Dollar-Mistake-Tony-Hoare">Null References: The Billion Dollar Mistake</a> ，而 js 里有两个 null（null 和 undefined），虽然前端通常不会造成非常严重的损失，但是 js 也慢慢被应用到不仅仅是前端的许多地方了。</p>
<p>ts 这么好，</p>
<h2 id="怎么学-TypeScript？"><a href="#怎么学-TypeScript？" class="headerlink" title="怎么学 TypeScript？"></a>怎么学 TypeScript？</h2><p>成也渐进，败也渐进，有部分人通过可选的类型标注，一步一步无痛地过渡到学会 ts。</p>
<p>而另一部分人玩了一会儿，发现和写 js 并没有一丁点区别，而且还离开了熟悉的环境，就放弃了。</p>
<p>ts 并不会强迫你使用类型，所以就需要更强的动力来推动自己学习。</p>
<p>如果身边有会 ts 的朋友的话，对学习 ts 会比较有帮助。</p>
<p>多让会 ts 的朋友看自己的代码，改良自己的写法。多写，很容易就能学会。</p>
<p>如果身边没有会 ts 的人，其实我更建议先用 <a href="https://github.com/Microsoft/TypeScript/wiki/JSDoc-support-in-JavaScript" target="_blank" rel="noopener">JSDoc</a>。</p>
<p>使用 vscode 或者 webstorm 的时候直接写 JSDoc 就行了，vsc 或 webstorm 会依靠 ts 来提供类型推导和自动完成。</p>
<p>这样可以在工作或自己写东西的时候慢慢习惯并且主动去使用类型标注。</p>
<p>在使用一段时间后感觉 JSDoc 已经不够用了，满足不了自己的需求了，再开始使用 ts。</p>
<p>同时也要多主动去了解和学习一些 ts 的代码，不然的话，不知道 ts 有多好，自然就不会觉得 JSDoc 不够用。</p>

            <!--[if lt IE 9]><script>document.createElement('audio');</script><![endif]-->
            <audio id="audio" loop="1" preload="auto" controls="controls"
                data-autoplay="false">
                <source type="audio/mpeg" src="">
            </audio>
            
            <ul id="audio-list" style="display:none">
                
                
                <li title='0' data-url='/statics/chengdu.mp3'></li>
                
                    
            </ul>
            
            
            
    <div id='gitalk-container' class="comment link"
        data-ae='true'
        data-ci='ec894e2b66f752e8b7fb'
        data-cs='3ccc2e92bb350688fe2c2dc2930189b62622bfb1'
        data-r='blog-comments'
        data-o='TriDiamond'
        data-a='TriDiamond'
        data-d='undefined'
    >Comments</div>


            
            
        </div>
        <div class="sidebar">
            <div class="box animated fadeInRight">
                <div class="subbox">
                    <img src="https://res.cloudinary.com/tridiamond/image/upload/v1573019751/TriDiamond_logo_ui_xeublz.jpg" height=300 width=300></img>
                    <p>张白告丶</p>
                    <span>Think like an artist, develop like an artisan</span>
                    <dl>
                        <dd><a href="https://github.com/zhanghao-web" target="_blank"><span
                                    class=" iconfont icon-github"></span></a></dd>
                        <dd><a href="" target="_blank"><span
                                    class=" iconfont icon-twitter"></span></a></dd>
                        <dd><a href="" target="_blank"><span
                                    class=" iconfont icon-stack-overflow"></span></a></dd>
                    </dl>
                </div>
                <ul>
                    <li><a href="/">149 <p>Articles</p></a></li>
                    <li><a href="/categories">23 <p>Categories</p></a></li>
                    <li><a href="/tags">47 <p>Tags</p></a></li>
                </ul>
            </div>
            
            
            
            <div class="box sticky animated fadeInRight faster">
                <div id="toc" class="subbox">
                    <h4>Contents</h4>
                    <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#静态类型有什么好处"><span class="toc-number">1.</span> <span class="toc-text">静态类型有什么好处</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#静态类型有什么不足"><span class="toc-number">2.</span> <span class="toc-text">静态类型有什么不足</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#TypeScript-的类型系统有哪些特点？"><span class="toc-number">3.</span> <span class="toc-text">TypeScript 的类型系统有哪些特点？</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#怎么学-TypeScript？"><span class="toc-number">4.</span> <span class="toc-text">怎么学 TypeScript？</span></a></li></ol>
                </div>
            </div>
            
            
        </div>
    </div>
</div>

    </div>
</div>
    <div id="back-to-top" class="animated fadeIn faster">
        <div class="flow"></div>
        <span class="percentage animated fadeIn faster">0%</span>
        <span class="iconfont icon-top02 animated fadeIn faster"></span>
    </div>
</body>
<footer>
    <p class="copyright" id="copyright">
        &copy; 2020
        <span class="gradient-text">
            张白告丶
        </span>.
        Powered by <a href="http://hexo.io/" title="Hexo" target="_blank" rel="noopener">Hexo</a>
        Theme
        <span class="gradient-text">
            <a href="https://github.com/TriDiamond/hexo-theme-obsidian" title="Obsidian" target="_blank" rel="noopener">Obsidian</a>
        </span>
        <small><a href="https://github.com/TriDiamond/hexo-theme-obsidian/blob/master/CHANGELOG.md" title="v1.4.3" target="_blank" rel="noopener">v1.4.3</a></small>
    </p>
</footer>

<script type="text/javascript" src="https://cdn.bootcss.com/mathjax/2.7.6/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
<script>
  MathJax.Hub.Config({
    "HTML-CSS": {
      preferredFont: "TeX",
      availableFonts: ["STIX", "TeX"],
      linebreaks: {
        automatic: true
      },
      EqnChunk: (MathJax.Hub.Browser.isMobile ? 10 : 50)
    },
    tex2jax: {
      inlineMath: [
        ["$", "$"],
        ["\\(", "\\)"]
      ],
      processEscapes: true,
      ignoreClass: "tex2jax_ignore|dno",
      skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
    },
    TeX: {
      noUndefined: {
        attributes: {
          mathcolor: "red",
          mathbackground: "#FFEEEE",
          mathsize: "90%"
        }
      },
      Macros: {
        href: "{}"
      }
    },
    messageStyle: "none"
  });
</script>
<script>
  function initialMathJax() {
    MathJax.Hub.Queue(function () {
      var all = MathJax.Hub.getAllJax(),
        i;
      // console.log(all);
      for (i = 0; i < all.length; i += 1) {
        console.log(all[i].SourceElement().parentNode)
        all[i].SourceElement().parentNode.className += ' has-jax';
      }
    });
  }

  function reprocessMathJax() {
    if (typeof MathJax !== 'undefined') {
      MathJax.Hub.Queue(["Typeset", MathJax.Hub]);
    }
  }
</script>



    
<link rel="stylesheet" href="//cdn.bootcss.com/gitalk/1.5.0/gitalk.min.css">

    
<script src="//cdn.bootcss.com/gitalk/1.5.0/gitalk.min.js"></script>



<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="/js/plugin.js"></script>
<script src="/js/obsidian.js"></script>
<script src="/js/jquery.truncate.js"></script>
<script src="/js/search.js"></script>


<script src="//cdn.bootcss.com/typed.js/2.0.10/typed.min.js"></script>


<script src="//cdn.bootcss.com/blueimp-md5/2.12.0/js/md5.min.js"></script>


<script src="//cdnjs.cloudflare.com/ajax/libs/social-share.js/1.0.16/js/social-share.min.js"></script>


<script src="https://cdn.bootcss.com/codemirror/5.48.4/codemirror.min.js"></script>

    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/javascript/javascript.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/css/css.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/xml/xml.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/htmlmixed/htmlmixed.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/clike/clike.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/php/php.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/shell/shell.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/python/python.min.js"></script>




    
<script src="/js/busuanzi.min.js"></script>

    <script>
        $(document).ready(function () {
            if ($('span[id^="busuanzi_"]').length) {
                initialBusuanzi();
            }
        });
    </script>



<link rel="stylesheet" href="//cdn.bootcss.com/photoswipe/4.1.3/photoswipe.min.css">
<link rel="stylesheet" href="//cdn.bootcss.com/photoswipe/4.1.3/default-skin/default-skin.min.css">


<script src="//cdn.bootcss.com/photoswipe/4.1.3/photoswipe.min.js"></script>
<script src="//cdn.bootcss.com/photoswipe/4.1.3/photoswipe-ui-default.min.js"></script>


<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">
    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>
    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">
        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>
        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">
            <div class="pswp__top-bar">
                <!--  Controls are self-explanatory. Order can be changed. -->
                <div class="pswp__counter"></div>
                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
                <button class="pswp__button pswp__button--share" title="Share"></button>
                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>
                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                      <div class="pswp__preloader__cut">
                        <div class="pswp__preloader__donut"></div>
                      </div>
                    </div>
                </div>
            </div>
            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div> 
            </div>
            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>
            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>
            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>
        </div>
    </div>
</div>



    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="//www.googletagmanager.com/gtag/js?id=UA-149874671-1"></script>
    <script>
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());

        gtag('config', 'UA-149874671-1');
    </script>





<script>
    function initialTyped () {
        var typedTextEl = $('.typed-text');
        if (typedTextEl && typedTextEl.length > 0) {
            var typed = new Typed('.typed-text', {
                strings: ["Think like an artist, develop like an artisan", "艺术家思维去思考问题，工匠创造精神去开发"],
                typeSpeed: 90,
                loop: true,
                loopCount: Infinity,
                backSpeed: 20,
            });
        }
    }

    if ($('.article-header') && $('.article-header').length) {
        $(document).ready(function () {
            initialTyped();
        });
    }
</script>




</html>
